package vn.ikame.android.boojtran.truyenbua.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.util.Log;

public class Download {
	private IDownloadHandler downloadHandler;
	private long size;
	private int index = -1;

	public Download(IDownloadHandler downloadHandler) {
		this.downloadHandler = downloadHandler;
	}

	public void DownloadFromUrl(int index, final String fileURL,
			final String fileName) {
		this.index = index;
		size = 0;
		Thread thr = new Thread() {
			public void run() {
				download(fileURL, fileName);
			}
		};
		thr.start();
	}

	public void DownloadFromUrl(final String fileURL, final String fileName) {
		size = 0;
		Thread thr = new Thread() {
			public void run() {
				download(fileURL, fileName);
			}
		};
		thr.start();
	}

	private void download(String fileURL, String fileNameSave) {
		try {
			URL url = new URL(fileURL);
			File file = new File(fileNameSave);
			File fileFolder = new File(file.getParent());
			if (!fileFolder.exists())
				fileFolder.mkdirs();
			long startTime = System.currentTimeMillis();
			Log.i("ImageManager", "download begining");
			Log.i("ImageManager", "download url:" + url);
			Log.i("ImageManager", "downloaded file name:" + fileNameSave);
			/* Open a connection to that URL. */
			URLConnection ucon = url.openConnection();
			ucon.setConnectTimeout(15000);
			int fileLength = ucon.getContentLength();

			/*
			 * Define InputStreams to read from the URLConnection.
			 */
			InputStream is = ucon.getInputStream();
			// BufferedInputStream bis = new BufferedInputStream(is);

			/*
			 * Read bytes to the Buffer until there is nothing more to read(-1).
			 */
			// ByteArrayBuffer baf = new ByteArrayBuffer(50);
			// int current = 0;
			// while ((current = bis.read()) != -1) {
			// size++;
			// baf.append((byte) current);
			// }
			//
			// /* Convert the Bytes read to a String. */
			FileOutputStream fos = new FileOutputStream(file);
			// fos.write(baf.toByteArray());
			byte data[] = new byte[1024];
			long total = 0;
			int count = 0;

			while ((count = is.read(data)) != -1) {
				total += count;
				fos.write(data, 0, count);
				downloadHandler
						.downloadProgress((int) (total * 100 / fileLength));
			}
			fos.flush();
			fos.close();
			is.close();
			ucon = null;
			Log.d("ImageManager",
					"download ready in"
							+ ((System.currentTimeMillis() - startTime) / 1000)
							+ " sec");
			if (total != fileLength) {
				if (downloadHandler != null)
					downloadHandler.onDownloadFinish(index, fileNameSave);
			} else {
				if (downloadHandler != null)
					downloadHandler.onDownloadError(index, fileNameSave);
			}

		} catch (IOException e) {
			e.printStackTrace();
			if (downloadHandler != null)
				downloadHandler.onDownloadError(index, fileNameSave);
		}
	}

	public long getDownloadedSize() {
		return size;
	}
}
